package com.chushouya.manager.service.common.impl;


import com.general.framework.core.constant.Constants;
import com.general.framework.core.exception.Ex;
import com.general.framework.data.redis.RedisCache;
import com.chushouya.manager.dao.entity.ConfigEntity;
import com.chushouya.manager.dao.repository.ConfigRepository;
import com.chushouya.manager.dto.admin.config.ConfigDTO;
import com.chushouya.manager.dto.admin.config.ConfigQuery;
import com.chushouya.manager.service.common.ConfigApiService;
import com.general.framework.core.lang.Beans;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 参数配置
 */
@Service
@Slf4j
public class ConfigApiServiceImpl implements ConfigApiService {

    @Resource
    private ConfigRepository configRepository;

    @Resource
    private RedisCache redisCache;

    @Override
    public ConfigDTO selectConfigByKey(String configKey) {
        ConfigDTO cacheConfig = redisCache.getCacheObject(this.getCacheKey(configKey));
        if (Objects.nonNull(cacheConfig)) {
            return cacheConfig;
        }
        ConfigQuery query = new ConfigQuery();
        query.setConfigKey(configKey);
        ConfigEntity configEntity = configRepository.selectOne(query);
        if (Objects.isNull(configEntity)) {
            throw Ex.business("不存在的系统参数:{}", configKey);

        }
        final ConfigDTO config = Beans.copy(configEntity, ConfigDTO.class);
        redisCache.setCacheObject(this.getCacheKey(configKey), config);
        return config;
    }

    /**
     * 设置cache key
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return Constants.CACHE_CONFIG_KEY + configKey;
    }

    @Override
    public String getStringConfig(String configKey) {
        return this.selectConfigByKey(configKey).getConfigValue();
    }

}
